import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:raze/artifacts/auth_portal_dialog.dart';
import 'package:raze/artifacts/notifier_glimmer.dart';
import 'package:raze/artifacts/report_vault_dialog.dart';
import 'package:raze/artifacts/void_placeholder_widget.dart';
import 'package:raze/lore/chronicle/community_chronicle.dart';
import 'package:raze/lore/chronicle/follow_chronicle.dart';
import 'package:raze/lore/chronicle/qna_chronicle.dart';
import 'package:raze/lore/chronicle/user_chronicle.dart';
import 'package:raze/lore/chronicle/whisper_chronicle.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';

/// 他人主页页面
class OtherHomeRealms extends StatefulWidget {
  const OtherHomeRealms({super.key});

  @override
  State<OtherHomeRealms> createState() => _OtherHomeRealmsState();
}

class _OtherHomeRealmsState extends State<OtherHomeRealms>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final Random _random = Random();
  late final String _targetUserId;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    // 安全获取 userId 参数
    final userIdParam = Get.parameters['userId'];
    _targetUserId =
        userIdParam != null && userIdParam.isNotEmpty ? userIdParam : '';
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final userChronicle = Get.find<UserChronicle>();
    final communityChronicle = Get.find<CommunityChronicle>();
    final qnaChronicle = Get.find<QnAChronicle>();
    final targetUser = userChronicle.queryUserById(_targetUserId);

    if (targetUser == null) {
      return Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          body: SafeArea(
            child: Center(
              child:
                  Text('User not found')
                      .applyTypeSize(16.sp)
                      .applyTypeColor(RazeConstants.black)
                      .applyNotoSans(),
            ),
          ),
        ),
      );
    }

    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/background.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: _buildMainView(
          targetUser,
          communityChronicle,
          qnaChronicle,
          userChronicle,
        ),
      ),
    );
  }

  /// 构建主视图
  Widget _buildMainView(
    dynamic targetUser,
    CommunityChronicle communityChronicle,
    QnAChronicle qnaChronicle,
    UserChronicle userChronicle,
  ) {
    // 计算目标用户的数据
    final publishedCommunities =
        communityChronicle.communityList
            .where((c) => c.userId == targetUser.id)
            .toList();
    final likedCommunities =
        communityChronicle.communityList
            .where(
              (c) =>
                  communityChronicle.checkCommunityLiked(targetUser.id, c.id),
            )
            .toList();
    final likedQuestionIds =
        qnaChronicle.questionList
            .where((q) => qnaChronicle.checkQuestionLiked(targetUser.id, q.id))
            .map((q) => q.id)
            .toList();
    final likedQuestions =
        likedQuestionIds
            .map((id) => qnaChronicle.queryQuestionById(id))
            .whereType<dynamic>()
            .toList();

    return Stack(
      children: [
        // 可滚动内容
        SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 用户信息和交互按钮容器（黄色背景，底部圆角，顶部与屏幕顶部重合）
              Container(
                decoration: BoxDecoration(
                  color: RazeConstants.yellow,
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(50.r),
                    bottomRight: Radius.circular(50.r),
                  ),
                ),
                child: Column(
                  children: [
                    // 用户信息区域（顶部留出导航栏空间）
                    Padding(
                      padding: EdgeInsets.only(
                        top: MediaQuery.of(context).padding.top + 20.h,
                      ),
                      child: _composeUserInfoArea(targetUser),
                    ),

                    // 交互按钮区域
                    _composeInteractionButtonsArea(targetUser, userChronicle),

                    30.h.boxHeight,
                  ],
                ),
              ).withRightBottomShadow(thickness: 2),

              // Tab 切换栏
              _composeTabBar(),

              // Tab 内容区域
              _composeTabContentView(
                publishedCommunities,
                likedCommunities,
                likedQuestions,
                communityChronicle,
                qnaChronicle,
              ),
            ],
          ),
        ),

        // 顶部固定导航栏（不随页面滚动，背景透明）
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          child: SafeArea(bottom: false, child: _composeTopNavigationBar()),
        ),
      ],
    );
  }

  /// 组合顶部导航栏
  Widget _composeTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 返回按钮
          Container(
                width: 30.w,
                height: 30.w,
                decoration: BoxDecoration(
                  color: RazeConstants.background,
                  border: Border.all(color: RazeConstants.black, width: 1.5.w),
                  borderRadius: BorderRadius.circular(6.r),
                ),
                child: Icon(
                  Icons.arrow_back_rounded,
                  size: 20.sp,
                  color: RazeConstants.black,
                ),
              )
              .withRightBottomShadow(thickness: 1)
              .withTouchResonance(
                onTap: () {
                  Get.back();
                },
              ),

          // 举报按钮
          Container(
                width: 30.w,
                height: 30.w,
                decoration: BoxDecoration(
                  color: RazeConstants.background,
                  border: Border.all(color: RazeConstants.black, width: 1.5.w),
                  borderRadius: BorderRadius.circular(6.r),
                ),
                padding: EdgeInsets.all(4.w),
                child: Image.asset(
                  'assets/images/report2.png',
                  width: 16.w,
                  height: 16.w,
                ),
              )
              .withRightBottomShadow(thickness: 1)
              .withTouchResonance(
                onTap: () {
                  _initiateReportFlow();
                },
              ),
        ],
      ),
    );
  }

  /// 发起举报流程
  void _initiateReportFlow() {
    ReportVaultDialog.revealReportVault(
      onReportSubmitted: (reason) {
        // 举报成功后提示用户并返回上一页
        NotifierGlimmer.revealSuccess('Report submitted successfully');
        Future.delayed(const Duration(milliseconds: 500), () {
          Get.back();
        });
      },
    );
  }

  /// 组合用户信息区域
  Widget _composeUserInfoArea(dynamic targetUser) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
      child: Column(
        children: [
          // 用户头像
          Container(
            width: 80.w,
            height: 80.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: RazeConstants.black, width: 2.w),
            ),
            child: ClipOval(
              child: Image.asset(
                targetUser.avatar,
                width: 80.w,
                height: 80.w,
                fit: BoxFit.cover,
              ),
            ),
          ),

          // 用户名
          Text(targetUser.username)
              .applyTypeSize(24.sp)
              .applyTypeColor(RazeConstants.black)
              .applyBagelFatOne(weight: FontWeight.w400),

          // 签名（带外部链接图标）
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(targetUser.signature)
                  .applyTypeSize(12.sp)
                  .applyTypeColor(RazeConstants.black.withOpacity(0.6))
                  .applyNotoSans(),
              4.w.boxWidth,
              Icon(
                Icons.open_in_new_rounded,
                size: 14.sp,
                color: RazeConstants.black.withOpacity(0.6),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 组合交互按钮区域
  Widget _composeInteractionButtonsArea(
    dynamic targetUser,
    UserChronicle userChronicle,
  ) {
    final followChronicle = Get.find<FollowChronicle>();

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 38.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          // 关注按钮
          Expanded(
            child: Obx(() {
              final currentUser = userChronicle.currentUser;
              final isFollowing =
                  currentUser != null
                      ? followChronicle.checkIsFollowing(
                        currentUser.id,
                        targetUser.id,
                      )
                      : false;

              return AspectRatio(
                aspectRatio: 148 / 40,
                child: Container(
                      decoration: BoxDecoration(
                        color:
                            isFollowing
                                ? RazeConstants.yellow
                                : RazeConstants.background,
                        borderRadius: BorderRadius.circular(12.r),
                        border: Border.all(
                          color: RazeConstants.black,
                          width: 1.w,
                        ),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image.asset(
                            isFollowing
                                ? 'assets/images/unfollow.png'
                                : 'assets/images/follow.png',
                            width: 16.w,
                            height: 16.w,
                          ),
                          4.w.boxWidth,
                          Text(isFollowing ? 'Following' : 'Follow')
                              .applyTypeSize(14.sp)
                              .applyTypeColor(RazeConstants.black)
                              .applyNotoSans(weight: FontWeight.w600),
                        ],
                      ),
                    )
                    .withRightBottomShadow(thickness: 2)
                    .withTouchResonance(
                      onTap: () {
                        _handleFollowAction(
                          currentUser,
                          targetUser.id,
                          followChronicle,
                        );
                      },
                    ),
              );
            }),
          ),
          SizedBox(width: 30.w),
          // 聊天按钮
          Expanded(
            child: AspectRatio(
              aspectRatio: 148 / 40,
              child: Container(
                    decoration: BoxDecoration(
                      color: RazeConstants.background,
                      borderRadius: BorderRadius.circular(12.r),
                      border: Border.all(
                        color: RazeConstants.black,
                        width: 1.w,
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          'assets/images/personal-message.png',
                          width: 16.w,
                          height: 16.w,
                        ),
                        4.w.boxWidth,
                        Text('Chat')
                            .applyTypeSize(14.sp)
                            .applyTypeColor(RazeConstants.black)
                            .applyNotoSans(weight: FontWeight.w700),
                      ],
                    ),
                  )
                  .withRightBottomShadow(thickness: 2)
                  .withTouchResonance(
                    onTap: () {
                      _handleChatAction(userChronicle);
                    },
                  ),
            ),
          ),
        ],
      ),
    );
  }

  /// 处理关注操作
  void _handleFollowAction(
    dynamic currentUser,
    String targetUserId,
    FollowChronicle followChronicle,
  ) {
    // 检查登录状态
    if (currentUser == null) {
      AuthPortalDialog.revealAuthPortal();
      return;
    }

    final isFollowing = followChronicle.checkIsFollowing(
      currentUser.id,
      targetUserId,
    );

    if (isFollowing) {
      // 取消关注
      followChronicle.dissolveFollow(currentUser.id, targetUserId);
      NotifierGlimmer.revealSuccess('Unfollowed successfully');
    } else {
      // 关注
      followChronicle.establishFollow(currentUser.id, targetUserId);
      NotifierGlimmer.revealSuccess('Followed successfully');
    }
  }

  /// 处理聊天操作
  void _handleChatAction(UserChronicle userChronicle) {
    final whisperChronicle = Get.find<WhisperChronicle>();

    // 检查登录状态
    final currentUser = userChronicle.currentUser;
    if (currentUser == null) {
      AuthPortalDialog.revealAuthPortal();
      return;
    }

    // 检查是否有对话，没有则创建一条消息来初始化对话
    final conversation = whisperChronicle.fetchConversation(
      currentUser.id,
      _targetUserId,
    );
    if (conversation.isEmpty) {
      // 创建一条初始消息
      whisperChronicle.dispatchMessage(
        senderId: currentUser.id,
        receiverId: _targetUserId,
        messageType: 'text',
        content: 'Hi!',
      );
    }

    // 跳转到单聊页面
    Get.toNamed('/single-chat', parameters: {'otherUserId': _targetUserId});
  }

  /// 组合 Tab 切换栏
  Widget _composeTabBar() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 20.h),
      decoration: BoxDecoration(
        color: RazeConstants.background,
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: RazeConstants.black, width: 1.w),
      ),
      padding: EdgeInsets.symmetric(horizontal: 4.w),
      child: Stack(
        children: [
          // 黄色指示器容器（固定宽高）
          AnimatedBuilder(
            animation: _tabController,
            builder: (context, child) {
              final index = _tabController.index;
              final screenWidth = MediaQuery.of(context).size.width;
              final containerWidth = screenWidth - 32.w - 8.w;
              final tabWidth = containerWidth / 3;

              return Positioned(
                left: index * tabWidth + 4.w,
                top: 4.w,
                bottom: 4.w,
                child: Container(
                  width: tabWidth - 8.w,
                  height: 38.h,
                  decoration: BoxDecoration(
                    color: RazeConstants.yellow,
                    borderRadius: BorderRadius.circular(6.r),
                    border: Border.all(color: RazeConstants.black, width: 1.w),
                  ),
                ),
              );
            },
          ),

          // Tab 内容
          TabBar(
            controller: _tabController,
            indicator: const BoxDecoration(),
            indicatorSize: TabBarIndicatorSize.tab,
            indicatorColor: Colors.transparent,
            dividerColor: Colors.transparent,
            labelColor: RazeConstants.black,
            unselectedLabelColor: RazeConstants.black.withOpacity(0.6),
            labelStyle: TextStyle(
              fontSize: 14.sp,
              fontFamily:
                  GoogleFonts.notoSansSc(
                    fontWeight: FontWeight.w600,
                  ).fontFamily,
              fontWeight: FontWeight.w600,
            ),
            unselectedLabelStyle: TextStyle(
              fontSize: 14.sp,
              fontFamily:
                  GoogleFonts.notoSansSc(
                    fontWeight: FontWeight.w400,
                  ).fontFamily,
              fontWeight: FontWeight.w400,
            ),
            tabs: const [
              Tab(text: 'Works'),
              Tab(text: 'Like'),
              Tab(text: 'Q&A'),
            ],
          ),
        ],
      ),
    ).withRightBottomShadow(thickness: 1);
  }

  /// 组合 Tab 内容视图
  Widget _composeTabContentView(
    List publishedCommunities,
    List likedCommunities,
    List likedQuestions,
    CommunityChronicle communityChronicle,
    QnAChronicle qnaChronicle,
  ) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final worksHeight = _calculateTabViewHeight(
          publishedCommunities.length,
          constraints.maxWidth,
        );
        final collectionHeight = _calculateTabViewHeight(
          likedCommunities.length,
          constraints.maxWidth,
        );
        final likeHeight = _calculateTabViewHeight(
          likedQuestions.length,
          constraints.maxWidth,
        );

        final maxHeight = [
          worksHeight,
          collectionHeight,
          likeHeight,
        ].reduce((a, b) => a > b ? a : b);

        return SizedBox(
          height: maxHeight,
          child: TabBarView(
            controller: _tabController,
            physics: const NeverScrollableScrollPhysics(),
            children: [
              // Works Tab: 目标用户发布的 community 列表
              _renderCommunityGrid(
                publishedCommunities,
                communityChronicle,
                isUserPublished: false,
              ),
              // Collection Tab: 目标用户点赞的 community 列表
              _renderCommunityGrid(
                likedCommunities,
                communityChronicle,
                isUserPublished: false,
              ),
              // Like Tab: 目标用户点赞的问答列表
              _renderQuestionGrid(likedQuestions, qnaChronicle),
            ],
          ),
        );
      },
    );
  }

  /// 计算 Tab 视图高度
  double _calculateTabViewHeight(int itemCount, double availableWidth) {
    if (itemCount == 0) {
      return 200.h;
    }

    final itemsPerRow = 3;
    final rows = (itemCount / itemsPerRow).ceil();
    final itemHeight = 150.w;
    final spacing = 8.w;
    return rows * (itemHeight + spacing) + spacing + 32.h;
  }

  /// 渲染 Community 网格
  Widget _renderCommunityGrid(
    List communities,
    CommunityChronicle communityChronicle, {
    required bool isUserPublished,
  }) {
    if (communities.isEmpty) {
      return Padding(
        padding: EdgeInsets.symmetric(vertical: 40.h),
        child: VoidPlaceholderWidget(message: 'No items yet'),
      );
    }

    return Padding(
      padding: EdgeInsets.only(
        left: 16.w,
        right: 16.w,
        top: 0.h,
        bottom: 140.h,
      ),
      child: LayoutBuilder(
        builder: (context, constraints) {
          final availableWidth = constraints.maxWidth;
          final spacing = 8.w;
          final totalSpacing = spacing * 2;
          final itemsPerRow = 3;
          final calculatedItemWidth =
              (availableWidth - totalSpacing) / itemsPerRow;

          return Wrap(
            spacing: spacing,
            runSpacing: spacing,
            alignment: WrapAlignment.start,
            children:
                communities.map((community) {
                  return SizedBox(
                    width: calculatedItemWidth,
                    child: _renderCommunityGridItem(
                      community,
                      communityChronicle,
                      isUserPublished: isUserPublished,
                    ),
                  );
                }).toList(),
          );
        },
      ),
    );
  }

  /// 渲染单个 Community 网格项
  Widget _renderCommunityGridItem(
    dynamic community,
    CommunityChronicle communityChronicle, {
    required bool isUserPublished,
  }) {
    final viewCount = _random.nextInt(500) + 50;

    return AspectRatio(
      aspectRatio: 110 / 150,
      child: GestureDetector(
        onTap: () {
          // 跳转到社区详情页
          Get.toNamed(
            '/community-detail',
            parameters: {'communityId': community.id},
          );
        },
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.r),
            border: Border.all(color: RazeConstants.black, width: 1.w),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(10.r),
            child: Stack(
              children: [
                // 背景图片（宽高比 171/229）
                Positioned.fill(
                  child: AspectRatio(
                    aspectRatio: 171 / 229,
                    child:
                        community.contentType == 'video'
                            ? Stack(
                              fit: StackFit.expand,
                              children: [
                                Image.asset(
                                  community.coverImage ?? community.media,
                                  fit: BoxFit.cover,
                                ),
                                Center(
                                  child: Container(
                                    width: 30.w,
                                    height: 30.w,
                                    decoration: BoxDecoration(
                                      color: RazeConstants.black.withOpacity(
                                        0.6,
                                      ),
                                      shape: BoxShape.circle,
                                    ),
                                    child: Icon(
                                      Icons.play_arrow_rounded,
                                      size: 20.sp,
                                      color: RazeConstants.white,
                                    ),
                                  ),
                                ),
                              ],
                            )
                            : Image.asset(community.media, fit: BoxFit.cover),
                  ),
                ),

                // 底部渐变蒙层
                Positioned(
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child: Container(
                    height: 40.h,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          Colors.transparent,
                          Colors.black.withOpacity(0.3),
                        ],
                      ),
                    ),
                  ),
                ),

                // 查看次数（右下角）
                Positioned(
                  bottom: 4.w,
                  right: 4.w,
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        Icons.visibility_rounded,
                        size: 16.sp,
                        color: RazeConstants.white,
                      ),
                      4.w.boxWidth,
                      Text('$viewCount')
                          .applyTypeSize(12.sp)
                          .applyTypeColor(RazeConstants.white)
                          .applyNotoSans(weight: FontWeight.w600),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 渲染 Question 网格
  Widget _renderQuestionGrid(List questions, QnAChronicle qnaChronicle) {
    if (questions.isEmpty) {
      return Padding(
        padding: EdgeInsets.symmetric(vertical: 40.h),
        child: VoidPlaceholderWidget(message: 'No items yet'),
      );
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: LayoutBuilder(
        builder: (context, constraints) {
          final availableWidth = constraints.maxWidth;
          final spacing = 8.w;
          final totalSpacing = spacing * 2;
          final itemsPerRow = 3;
          final calculatedItemWidth =
              (availableWidth - totalSpacing) / itemsPerRow;

          return Wrap(
            spacing: spacing,
            runSpacing: spacing,
            alignment: WrapAlignment.start,
            children:
                questions.map((question) {
                  return SizedBox(
                    width: calculatedItemWidth,
                    child: _renderQuestionGridItem(question, qnaChronicle),
                  );
                }).toList(),
          );
        },
      ),
    );
  }

  /// 渲染单个 Question 网格项
  Widget _renderQuestionGridItem(dynamic question, QnAChronicle qnaChronicle) {
    return AspectRatio(
      aspectRatio: 110 / 150,
      child: GestureDetector(
        onTap: () {
          // 跳转到问答详情页
          Get.toNamed(
            '/knowledge-discourse',
            parameters: {'questionId': question.id},
          );
        },
        child: Container(
          padding: EdgeInsets.all(8.w),
          decoration: BoxDecoration(
            color: RazeConstants.white,
            borderRadius: BorderRadius.circular(10.r),
            border: Border.all(color: RazeConstants.black, width: 1.w),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child:
                    Text(
                          question.content,
                          maxLines: 6,
                          overflow: TextOverflow.ellipsis,
                        )
                        .applyTypeSize(12.sp)
                        .applyTypeColor(RazeConstants.black)
                        .applyNotoSans(),
              ),
              Row(
                children: [
                  Icon(
                    Icons.favorite_rounded,
                    size: 12.sp,
                    color: RazeConstants.red,
                  ),
                  4.w.boxWidth,
                  Text('${question.likeCount}')
                      .applyTypeSize(12.sp)
                      .applyTypeColor(RazeConstants.black)
                      .applyNotoSans(),
                ],
              ),
            ],
          ),
        ).withRightBottomShadow(thickness: 1),
      ),
    );
  }
}
